package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sc.nft.dao.*;
import com.sc.nft.dto.*;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.*;
import com.sc.nft.entity.vo.*;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.DigitalCollectionService;
import com.sc.nft.service.SecondCollectionConfigService;
import com.sc.nft.sup.ErrorCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 藏品表服务接口实现
 *
 * @author zxy
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2022-06-03 15:46:04
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DigitalCollectionServiceImpl implements DigitalCollectionService {

    private final DigitalCollectionDao digitalCollectionDao;

    private final DigitalCollectionProductInfoDao digitalCollectionProductInfoDao;

    private final CollectionChainInitDetailsLogDao collectionChainInitDetailsLogDao;

    private final UserChainInfoDao userChainInfoDao;

    private final ProductStockDao productStockDao;

    private final ProductCdkDao productCdkDao;

    private final UserCollectionDao userCollectionDao;

    private final UserCreatorInfoDao userCreatorInfoDao;

    private final StaticDataDao staticDataDao;

    private final CatenaInfoDao catenaInfoDao;

    private final BoxTakePoolDao boxTakePoolDao;
    private final SecondCollectionConfigService secondCollectionConfigService;
    private final SearchRelevanceDao searchRelevanceDao;
    private final CollectionGiftDao collectionGiftDao;
    private final UserEcologyHatchRecordsDao userEcologyHatchRecordsDao;
    private final AirdropGrantRecordDao airdropGrantRecordDao;
    private final UserInfoDao userInfoDao;
    private final CollecionLinkContrastRecordsDao collecionLinkContrastRecordsDao;
    private final DigitalCollectionProductInfoSubscribeDao digitalCollectionProductInfoSubscribeDao;
    private final EcologyHatchShareProfitDao ecologyHatchShareProfitDao;
    private final DigitalCollectionProductInfoAuctionDao digitalCollectionProductInfoAuctionDao;

    @Override
    public IPage<MallCollectionVO> pageDaoCollection(MallDaoCollectionDTO mallDaoCollectionDTO) {
        LambdaQueryWrapper<DigitalCollection> wr = Wrappers.lambdaQuery();
        wr.like(StringUtils.isNotBlank(mallDaoCollectionDTO.getCollectionName()), DigitalCollection::getFirstTitle, mallDaoCollectionDTO.getCollectionName());
        wr.eq(Objects.nonNull(mallDaoCollectionDTO.getDaoId()), DigitalCollection::getUserCreatorId, mallDaoCollectionDTO.getDaoId());
        wr.orderByDesc(DigitalCollection::getId);
        Page<DigitalCollection> page = digitalCollectionDao.page(new Page<>(mallDaoCollectionDTO.getPageNo(), mallDaoCollectionDTO.getPageSize()), wr);
        return page.convert(x -> {
            MallCollectionVO mallCollectionVO = new MallCollectionVO();
            mallCollectionVO.setCollectionId(x.getId());
            mallCollectionVO.setFirstTitle(x.getFirstTitle());
            mallCollectionVO.setCreationContent(x.getCreationContent());
            return mallCollectionVO;
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCollection(AddDigitalCollectionDTO addDigitalCollectionDTO) {
        DigitalCollection digitalCollection = BeanUtil.toBean(addDigitalCollectionDTO, DigitalCollection.class);
        if (ObjectUtil.isNotNull(this.getByTitle(addDigitalCollectionDTO.getFirstTitle()))) {
            throw new GlobalRunTimeException("标题已存在");
        }
        basicParameterVerification(digitalCollection);
        digitalCollection.setGasCost(addDigitalCollectionDTO.getConsumeCost());
        digitalCollection.setUsableCount(digitalCollection.getSumCount());
        digitalCollection.setDigitalCollectionUuid(UUID.fastUUID().toString().replaceAll("-", ""));
        digitalCollection.setNewDeal(digitalCollection.getIssuePrice());
        digitalCollection.setAntiHoardRatio(addDigitalCollectionDTO.getAntiHoardRatio().divide(Convert.toBigDecimal(100)).setScale(4, BigDecimal.ROUND_DOWN));
        if (addDigitalCollectionDTO.getCollectionType() == DigitalMarketTypeEnum.ECOLOGY) {
            digitalCollection.setAntiHoardCount(1);
            digitalCollection.setAntiHoardRatio(Convert.toBigDecimal(5).movePointLeft(2));
        }
        // 锁仓天数在V4.9.0需求中 藏品表中的字段废弃,迁移至商品表中 需求开始时间2023-12-12日,所有的锁仓天数都是0不在使用.
        digitalCollection.setLockupDays(0);
        digitalCollection.insert();
        //为藏品增加属性关联
        SearchRelevance searchRelevance = new SearchRelevance();
        searchRelevance.setCollectionId(digitalCollection.getId());
        searchRelevance.setSearchId(addDigitalCollectionDTO.getCollectionSearch());
        searchRelevance.insert();
        // 不管他开没开起来转赠,都要有初始化的数据,如果没开启 就都给0
        CollectionGiftTransitionDTO addEquityPropsCT = new CollectionGiftTransitionDTO();
        addEquityPropsCT.transition(addDigitalCollectionDTO.getAddEquityPropsGiftDTO(), digitalCollection.getId(), addDigitalCollectionDTO.getIsGive());
        addEquityPropsCT.addCrossChainTransition(addDigitalCollectionDTO.getMateWalleGiveEquityPropsGiftDTO(), digitalCollection.getId(), addDigitalCollectionDTO.getIsGiveImeta());
        collectionGiftDao.saveBatch(addEquityPropsCT.getList());
    }

    private static void basicParameterVerification(DigitalCollection digitalCollection) {
        if (digitalCollection.getProductDetailPictureType() == 3 && ObjectUtil.isEmpty(digitalCollection.getThreeModelId())) {
            throw new GlobalRunTimeException("设置3d模型必须填写3d模型id请联系安卓开发获取");
        }
        //生态藏品 给个初始值(用不到)
        if (digitalCollection.getAntiHoardCount() != null && digitalCollection.getAntiHoardRatio() == null) {
            throw new GlobalRunTimeException("防囤收益未配置");
        }
    }


    @Override
    public DigitalCollection getByTitle(String firstTitle) {
        return digitalCollectionDao.getByTitle(firstTitle);
    }

    @Override
    public Page<DigitalCollectionVO> page(String firstTitle, Long userCreatorId, Long catenaId, int pageNo, int pageSize, DigitalMarketTypeEnum collectionType, Long searchId) {
        Page<DigitalCollectionVO> page = digitalCollectionDao.page(firstTitle, userCreatorId, catenaId, pageNo, pageSize, collectionType, searchId);
        List<DigitalCollectionVO> records = page.getRecords();
        if (ObjectUtil.isNotNull(records)) {
            for (DigitalCollectionVO digitalCollectionVO : records) {
                Search search = searchRelevanceDao.getByCollectionId(digitalCollectionVO.getId());
                if (ObjectUtil.isNotNull(search)) {
                    digitalCollectionVO.setCollectionSearch(search.getId());
                    digitalCollectionVO.setCollectionSearchName(search.getSearchTitle());
                }
                List<CollectionGift> collectionGifts = collectionGiftDao.getCollectionId(digitalCollectionVO.getId());
                digitalCollectionVO.conversionConfiguration(collectionGifts);
                //转换成跨链转赠配置
                digitalCollectionVO.conversionMateWalletGiveGiftVO(collectionGiftDao.getConfListByCollectionIdAndType(digitalCollectionVO.getId(), CollectionOriginalTypeEnum.MATE_WALLET));

                CollecionLinkContrastRecords contrastRecords = collecionLinkContrastRecordsDao.getOneByCollectionId(digitalCollectionVO.getId());
                if (ObjectUtil.isNull(contrastRecords)) {
                    digitalCollectionVO.setLinkStatus(1);
                } else {
                    if (CollectionContractStatusEnum.INIT.equals(digitalCollectionVO.getContractStatus())) {
                        digitalCollectionVO.setLinkStatus(2);
                    } else {
                        digitalCollectionVO.setLinkStatus(3);
                    }
                }

            }
        }
        return page;
    }

    @Override
    public List<DigitalCollection> simpleList(String firstTitle, Long userCreatorId) {
        return digitalCollectionDao.simpleList(firstTitle, userCreatorId);
    }

    @Override
    public Page<PageSynthesisCollectionVO> pageSynthesisCollection(int pageNo, int pageSize, String firstTitle, Boolean isPrivilege) {

        return digitalCollectionDao.pageSynthesisCollection(pageNo, pageSize, firstTitle, isPrivilege);
    }

    @Override
    public Page<CollectionSimpleVO> pageRelatedCollections(String firstTitle, int pageNo, int pageSize) {
        return digitalCollectionDao.pageRelatedCollections(firstTitle, pageNo, pageSize);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDigitalCollection(UpdateDigitalCollectionDTO updateDigitalCollectionDTO) {

        checkCirculationType(updateDigitalCollectionDTO);//校验流通类型是否为空  这里和新增的校验有区别因为藏品类型在编辑的时候并没有传过来 实际上应该也要用id查出来去校验

        DigitalCollection digitalCollection = BeanUtil.toBean(updateDigitalCollectionDTO, DigitalCollection.class);
        basicParameterVerification(digitalCollection);
        if (ObjectUtil.isNull(digitalCollection.getId())) {
            throw new GlobalRunTimeException("藏品id不能为空");
        }
        digitalCollection.setGasCost(updateDigitalCollectionDTO.getConsumeCost());
        digitalCollection.updateById();
        List<DigitalCollectionProductInfo> byCollectionId = digitalCollectionProductInfoDao.selectByCollectionId(digitalCollection.getId(), ClassifyType.COLLECTION);
        for (DigitalCollectionProductInfo digitalCollectionProductInfo : byCollectionId) {
            digitalCollectionProductInfo.setCreationContent(digitalCollection.getCreationContent());
            digitalCollectionProductInfo.setProductDetailPicture(digitalCollection.getProductDetailPicture());
            digitalCollectionProductInfo.setProductDetailPictureType(digitalCollection.getProductDetailPictureType());
            digitalCollectionProductInfo.setProductPresentation(digitalCollection.getProductPresentation());
            digitalCollectionProductInfo.setPrivilegePresentation(digitalCollection.getPrivilegePresentation());
            digitalCollectionProductInfo.setThreeModelId(digitalCollection.getThreeModelId());
            digitalCollectionProductInfo.setSkipUrl(digitalCollection.getSkipUrl());
            digitalCollectionProductInfo.setShowLevel(digitalCollection.getShowLevel());
            digitalCollectionProductInfo.setUserCreatorId(digitalCollection.getUserCreatorId());
            digitalCollectionProductInfo.updateById();
        }
        //同步更新藏品属性关联表 先删除 后新增
        searchRelevanceDao.removeByCollectionId(digitalCollection.getId());
        SearchRelevance searchRelevance = new SearchRelevance();
        searchRelevance.setCollectionId(digitalCollection.getId());
        searchRelevance.setSearchId(updateDigitalCollectionDTO.getCollectionSearch());
        searchRelevance.insert();

        // 开启了转增
        if (digitalCollection.getIsGive()) {
            // 删掉所有的转增配置后重新新增
            collectionGiftDao.deleteByCollectionId(digitalCollection.getId());
            CollectionGiftTransitionDTO addEquityPropsCT = new CollectionGiftTransitionDTO();
            addEquityPropsCT.transition(updateDigitalCollectionDTO.getAddEquityPropsGiftDTO(), digitalCollection.getId(), digitalCollection.getIsGive());
            addEquityPropsCT.addCrossChainTransition(updateDigitalCollectionDTO.getMateWalleGiveEquityPropsGiftDTO(), digitalCollection.getId(), digitalCollection.getIsGiveImeta());
            collectionGiftDao.saveBatch(addEquityPropsCT.getList());
        }
    }

    private void checkCirculationType(UpdateDigitalCollectionDTO updateDigitalCollectionDTO) {
        DigitalCollection dc = digitalCollectionDao.getById(updateDigitalCollectionDTO.getId());
        if (Objects.isNull(dc)) {
            throw new GlobalRunTimeException("藏品不存在:" + updateDigitalCollectionDTO.getId());
        }
        if (dc.getCollectionType() == DigitalMarketTypeEnum.ECOLOGY && Objects.isNull(updateDigitalCollectionDTO.getCirculationType())) {
            throw new GlobalRunTimeException("流通类型不能为空");
        }
    }

    @Override
    public Page<HomePageDigitalCollectionProductVO> digitalcollectionByUserCreatorId(DigitalcollectionByUserCreatorIdDTO digitalcollectionByUserCreatorId) {
        digitalcollectionByUserCreatorId.setIsIosShow(0);
        Page<HomePageDigitalCollectionProductVO> homePageDigitalCollectionProductVOPage = digitalCollectionDao.digitalcollectionByUserCreatorId(digitalcollectionByUserCreatorId);
        for (HomePageDigitalCollectionProductVO digitalCollectionProductVO : homePageDigitalCollectionProductVOPage.getRecords()) {

            if (digitalCollectionProductVO.getTypeClassify() == ClassifyType.COLLECTION) {
                DigitalCollection digitalCollection = digitalCollectionDao.getById(digitalCollectionProductVO.getRelationId());
                digitalCollectionProductVO.setProductCount(digitalCollection.getSumCount());
            } else {
                ProductStock productStock = productStockDao.getProductStock(digitalCollectionProductVO.getProductId(), digitalCollectionProductVO.getRelationId(), null);
                digitalCollectionProductVO.setProductCount(productStock.getSumCount());
            }

            List timeList = new ArrayList();
            //region 首页申购
            if (digitalCollectionProductVO.getCommodityType() == CommodityType.SUBSCRIBE_COMMODITY) {
                DigitalCollectionProductInfoSubscribe digitalCollectionProductInfoSubscribe = digitalCollectionProductInfoSubscribeDao.getByProductInfoSubscribe(digitalCollectionProductVO.getProductId());
                if (Objects.nonNull(digitalCollectionProductInfoSubscribe)) {
                    timeList.add(DateUtil.format(digitalCollectionProductInfoSubscribe.getSubscribeStartTime(), "MM-dd HH:mm") + " 开始申购");
                    timeList.add(DateUtil.format(digitalCollectionProductInfoSubscribe.getConsistenceStartTime(), "MM-dd HH:mm") + " 开始抽签");
                    timeList.add(DateUtil.format(digitalCollectionProductInfoSubscribe.getConsistenceEndTime(), "MM-dd HH:mm") + " 公布结果");
                    if (ObjectUtil.isNotEmpty(digitalCollectionProductVO.getBeginTime())) {
                        Date date = DateUtil.parse(digitalCollectionProductVO.getBeginTime(), "yyyy-MM-dd HH:mm:ss");
                        digitalCollectionProductVO.setBeginTime(DateUtil.format(date, "MM-dd HH:mm"));
                        String format = DateUtil.format(date, "MM-dd HH:mm");
                        timeList.add(format + " 开始购买");
                    }
                }
            } else if (digitalCollectionProductVO.getCommodityType() == CommodityType.AUCTION_PRODUCT) {
                DigitalCollectionProductInfoAuction digitalCollectionProductInfoAuction = digitalCollectionProductInfoAuctionDao.getByProductId(digitalCollectionProductVO.getProductId());
                if (Objects.nonNull(digitalCollectionProductInfoAuction)) {
                    Date date = new Date();
                    if (date.before(digitalCollectionProductInfoAuction.getAuctionStartTime())) {
                        timeList.add(DateUtil.format(digitalCollectionProductInfoAuction.getAuctionStartTime(), "MM-dd HH:mm") + " 开始拍卖");
                    } else if (date.after(digitalCollectionProductInfoAuction.getAuctionStartTime()) && date.before(digitalCollectionProductInfoAuction.getAuctionEndTime())) {
                        timeList.add("进行中");
                    } else {
                        timeList.add("已结束");
                    }
                }
            } else if (ObjectUtil.isNotEmpty(digitalCollectionProductVO.getBeginTime())) {
                Date date = DateUtil.parse(digitalCollectionProductVO.getBeginTime(), "yyyy-MM-dd HH:mm:ss");
                digitalCollectionProductVO.setBeginTime(DateUtil.format(date, "MM-dd HH:mm"));
                String format = DateUtil.format(date, "MM-dd HH:mm");
                timeList.add(format + " 发售");
            }
            //endregion
            if (ObjectUtil.isNotEmpty(digitalCollectionProductVO.getPriorityPurchaseBeginTime())
                    && Objects.nonNull(digitalCollectionProductVO.getIsPriorityPurchase())
                    && digitalCollectionProductVO.getIsPriorityPurchase()) {
                Date date = DateUtil.parse(digitalCollectionProductVO.getPriorityPurchaseBeginTime(), "yyyy-MM-dd HH:mm:ss");
                digitalCollectionProductVO.setPriorityPurchaseBeginTime(DateUtil.format(date, "MM-dd HH:mm"));
                String format = DateUtil.format(date, "MM-dd HH:mm");
                timeList.add(format + " 优先购");
            }
            if (ObjectUtil.isNotEmpty(digitalCollectionProductVO.getRushBuyBeginTime())
                    && Objects.nonNull(digitalCollectionProductVO.getIsRushBuy())
                    && digitalCollectionProductVO.getIsRushBuy()) {
                Date date = DateUtil.parse(digitalCollectionProductVO.getRushBuyBeginTime(), "yyyy-MM-dd HH:mm:ss");
                digitalCollectionProductVO.setRushBuyBeginTime(DateUtil.format(date, "MM-dd HH:mm"));
                String format = DateUtil.format(date, "MM-dd HH:mm");
                timeList.add(format + " 优先抢");
            }
            digitalCollectionProductVO.setList(timeList);
        }
        return homePageDigitalCollectionProductVOPage;
    }


    @Override
    public List<GetAdminCollectionVO> getCollectionList(Long id) {
        return digitalCollectionDao.getCollectionList(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void collectionInitChain(DigitalCollection collection) {
        //修改状态
        Assert.isTrue(digitalCollectionDao.updateChainStatus(collection.getId(), CollectionChainStatusEnum.ON_THE_CHAIN), () -> new GlobalRunTimeException(ErrorCode.FAIL_TO_EDIT));
        //1为默认地址
        UserChainInfo userChainInfo = userChainInfoDao.getById(1);

        ArrayList<CollectionChainInitDetailsLog> list = Lists.newArrayList();
        //初始化链记录
        for (int i = 0; i < collection.getSumCount(); i++) {
            CollectionChainInitDetailsLog chain = new CollectionChainInitDetailsLog();
            chain.setCollectionId(collection.getId());
            chain.setContractAddress(collection.getContractAddress());
            chain.setStatus(UserChainLogStatusEnum.WAIT);
            chain.setDealStatus(CollectionChainDealStatusEnum.IN_CHINA);
            chain.setUserAddress(userChainInfo.getAddress());
            chain.setCollectionUuid(IdUtil.getSnowflakeNextIdStr());
            chain.setDeployTransactionHash(collection.getDeployTransactionHash());
            list.add(chain);
        }
        log.info("list size:{}", list.size());
        List<List<CollectionChainInitDetailsLog>> split = CollUtil.split(list, 10000);
        for (List<CollectionChainInitDetailsLog> collectionChainInitDetailsLogs : split) {
            collectionChainInitDetailsLogDao.insertBatch(collectionChainInitDetailsLogs);
        }
    }

    @Override
    public Page<CollectionListAccordingDaoVO> getCollectionListAccordingDao(CollectionListAccordingDaoDTO collectionListAccordingDaoDTO) {
        return digitalCollectionDao.getCollectionListAccordingDao(collectionListAccordingDaoDTO);
    }

    @Override
    public Page<BoxCollectionByUserCreatorIdVO> boxCollectionByUserCreatorId(Long userCreatorId, Integer pageNo, Integer pageSize) {
        Page<BoxCollectionByUserCreatorIdVO> page = digitalCollectionProductInfoDao.getPageBoxCollectionByUserCreatorId(userCreatorId, pageNo, pageSize);
        for (BoxCollectionByUserCreatorIdVO box : page.getRecords()) {

            ProductStock productStock = productStockDao.getProductStock(box.getBlindBoxId(), box.getRelationId(), null);
            box.setProductCount(productStock.getSumCount());
            List timeList = new ArrayList();
            if (ObjectUtil.isNotEmpty(box.getBeginTime())) {
                Date date = DateUtil.parse(box.getBeginTime(), "yyyy-MM-dd HH:mm:ss");
                box.setBeginTime(DateUtil.format(date, "MM-dd HH:mm"));
                String format = DateUtil.format(date, "MM-dd HH:mm");
                timeList.add(format + " 发售");
            }
            if (ObjectUtil.isNotEmpty(box.getPriorityPurchaseBeginTime())) {
                Date date = DateUtil.parse(box.getPriorityPurchaseBeginTime(), "yyyy-MM-dd HH:mm:ss");
                box.setPriorityPurchaseBeginTime(DateUtil.format(date, "MM-dd HH:mm"));
                String format = DateUtil.format(date, "MM-dd HH:mm");
                timeList.add(format + " 优先购");
            }
            if (ObjectUtil.isNotEmpty(box.getRushBuyBeginTime())) {
                Date date = DateUtil.parse(box.getRushBuyBeginTime(), "yyyy-MM-dd HH:mm:ss");
                box.setRushBuyBeginTime(DateUtil.format(date, "MM-dd HH:mm"));
                String format = DateUtil.format(date, "MM-dd HH:mm");
                timeList.add(format + " 优先抢");
            }
            box.setList(timeList);
        }

        return page;
    }

    @Override
    public Page<AdminPageFreeMarketCollectionVO> getAdminPageFreeMarketCollection(Integer pageNo, Integer pageSize, String firstTitle) {
        return digitalCollectionDao.getAdminPageFreeMarketCollection(pageNo, pageSize, firstTitle);
    }

    @Override
    public GetDetailsBasedOnTheCollectionIdVO getDetailsBasedOnTheCollectionId(Long id) {
        GetDetailsBasedOnTheCollectionIdVO getDetailsBasedOnTheCollectionIdVO = new GetDetailsBasedOnTheCollectionIdVO();
        BoxTakePool boxTakePool = boxTakePoolDao.getById(id);
        if (BeanUtil.isEmpty(boxTakePool)) {
            throw new GlobalRunTimeException(ErrorCode.EXCHANGE_CAP);
        }
        DigitalCollectionProductInfo digitalCollectionProductInfo = digitalCollectionProductInfoDao.getById(boxTakePool.getProductBoxId());
        ProductStock byProductId = productStockDao.getByProductId(digitalCollectionProductInfo.getId());
        getDetailsBasedOnTheCollectionIdVO.setResidue(byProductId.getUsableCount());
        DigitalCollection digitalCollection = digitalCollectionDao.getById(digitalCollectionProductInfo.getRelationId());
        UserCreatorInfo byId = userCreatorInfoDao.getById(digitalCollectionProductInfo.getUserCreatorId());
        getDetailsBasedOnTheCollectionIdVO.setDaoName(byId.getDaoName());
        if (BeanUtil.isEmpty(digitalCollection)) {
            throw new GlobalRunTimeException(ErrorCode.EXCHANGE_FAIL);
        }
        //查询用户已购买记录
        MyCollectionNowVO collectionNowVO = userCollectionDao.countMyCollectionNow(UserPool.getUser().getId(), boxTakePool.getProductBoxId(), id);
        getDetailsBasedOnTheCollectionIdVO.setRedeemedQuantity(Objects.isNull(collectionNowVO) ? 0 : collectionNowVO.getCount());

        //填充兑换限制标记  0-未开始 1-已开始  2-已结束
        fillingRedeem(getDetailsBasedOnTheCollectionIdVO, digitalCollectionProductInfo);
        getDetailsBasedOnTheCollectionIdVO.setBeginTime(digitalCollectionProductInfo.getBeginTime());
        getDetailsBasedOnTheCollectionIdVO.setEndTime(digitalCollectionProductInfo.getEndTime());
        getDetailsBasedOnTheCollectionIdVO.setCollectionId(id);
        getDetailsBasedOnTheCollectionIdVO.setFirstTitle(digitalCollection.getFirstTitle());
        getDetailsBasedOnTheCollectionIdVO.setProductDetailPicture(digitalCollection.getProductDetailPicture());
        getDetailsBasedOnTheCollectionIdVO.setProductDetailPictureType(digitalCollection.getProductDetailPictureType());
        getDetailsBasedOnTheCollectionIdVO.setSumCount(digitalCollection.getSumCount());
        getDetailsBasedOnTheCollectionIdVO.setProductBoxId(boxTakePool.getProductBoxId());
        getDetailsBasedOnTheCollectionIdVO.setProductPresentation(digitalCollection.getProductPresentation());
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(digitalCollection.getUserCreatorId());
        getDetailsBasedOnTheCollectionIdVO.setNickName(userCreatorInfo.getNickName());
        getDetailsBasedOnTheCollectionIdVO.setCreatorAvatarImg(userCreatorInfo.getCreatorAvatarImg());
        StaticData staticData = staticDataDao.getByType("purchase_notes");
        getDetailsBasedOnTheCollectionIdVO.setPurchaseNotes(staticData.getValue());
        CatenaInfo catenaInfo = catenaInfoDao.getById(digitalCollection.getCatenaId());
        getDetailsBasedOnTheCollectionIdVO.setCatenaName(catenaInfo.getName());
        getDetailsBasedOnTheCollectionIdVO.setPrivilegePresentation(digitalCollection.getPrivilegePresentation());
        getDetailsBasedOnTheCollectionIdVO.setCountdown(0L);
        getDetailsBasedOnTheCollectionIdVO.setThreeModelId(digitalCollection.getThreeModelId());
        getDetailsBasedOnTheCollectionIdVO.setCreationContent(digitalCollection.getCreationContent());
        getDetailsBasedOnTheCollectionIdVO.setModelImg(digitalCollection.getModelImg());
        getDetailsBasedOnTheCollectionIdVO.setModelDistance(digitalCollection.getModelDistance());
        getDetailsBasedOnTheCollectionIdVO.setIsLockedPosition(digitalCollectionProductInfo.getIsLockedPosition());
        getDetailsBasedOnTheCollectionIdVO.setLockedPositionType(digitalCollectionProductInfo.getLockedPositionType());
        getDetailsBasedOnTheCollectionIdVO.setLockedPositionHour(digitalCollectionProductInfo.getLockedPositionHour());
        getDetailsBasedOnTheCollectionIdVO.setLockedPositionTime(digitalCollectionProductInfo.getLockedPositionTime());
        getDetailsBasedOnTheCollectionIdVO.setLockedPositionDescribe();
        getDetailsBasedOnTheCollectionIdVO.setUpperLimit(boxTakePool.getUpperLimit());
        getDetailsBasedOnTheCollectionIdVO.setSurplusCount();

        getDetailsBasedOnTheCollectionIdVO.setIsRegisterTime(digitalCollectionProductInfo.getIsRegisterTime());
        getDetailsBasedOnTheCollectionIdVO.setRegisterBeginTime(digitalCollectionProductInfo.getRegisterBeginTime());
        getDetailsBasedOnTheCollectionIdVO.setRegisterEndTime(digitalCollectionProductInfo.getRegisterEndTime());
        UserInfo user = UserPool.getUser();
        if (digitalCollectionProductInfo.getIsRegisterTime()) {
            if (user.getCreateTime().after(digitalCollectionProductInfo.getRegisterBeginTime()) && user.getCreateTime().before(digitalCollectionProductInfo.getRegisterEndTime())) {
                getDetailsBasedOnTheCollectionIdVO.setIsConforRegisterTime(Boolean.TRUE);
            }
        }
        return getDetailsBasedOnTheCollectionIdVO;
    }

    @Override
    public Page<CollectionSimpleVO> getPageCollection(Integer pageNo, Integer pageSize, String firstTitle) {
        return digitalCollectionDao.getAdminPageCollection(pageNo, pageSize, firstTitle);
    }

    @Override
    public Page<CollectionSimpleVO> getPageSecondaryMarketCollection(Integer pageNo, Integer pageSize) {
        return secondCollectionConfigService.getPageSecondaryMarketCollection(pageNo, pageSize);
    }

    @Override
    public List<AccessToCopyrightCollectionVO> accessToCopyrightCollection(AccessToCopyrightCollectioDTO accessToCopyrightCollectioDTO) {
        return digitalCollectionDao.accessToCollection(accessToCopyrightCollectioDTO);
    }

    @Override
    public List<AccessToCopyrightCollectionVO> collectionBindingCity(AccessToCopyrightCollectioDTO accessToCopyrightCollectioDTO) {
        return digitalCollectionDao.collectionBindingCity(accessToCopyrightCollectioDTO);
    }

    @Override
    public Page<CollectionSimpleVO> getCollectionPageByCollectionType(Integer pageNo, Integer pageSize) {
        return digitalCollectionDao.getCollectionPageByCollectionType(pageNo, pageSize);
    }

    @Override
    public Page<SimpleListByCollectionTypeVO> simpleListByCollectionType(Integer collectionType, String firstTitle, Integer pageNo, Integer pageSize, Long daoId) {
        return digitalCollectionDao.simpleListByCollectionType(collectionType, firstTitle, pageNo, pageSize, daoId);
    }

    @Override
    public IPage<CollectionSimpleVO> collectionSimpleListPage(String firstTitle, Long userCreatorId, Page mp, SaasTaskTypeEnum typeEnum) {
        return digitalCollectionDao.collectionSimpleListPage(firstTitle, userCreatorId, mp, typeEnum);
    }

    @Override
    public List<LargeDiskAccessVO> largeDiskAccess() {
        List<CycleCollection> cycleCollections = digitalCollectionDao.largeDiskAccess();
        return cycleCollections.stream().map(c -> {
            if (ObjectUtil.isNull(c.getDataValue())) {
                return new LargeDiskAccessVO();
            }
            return JSON.parseObject(c.getDataValue(), LargeDiskAccessVO.class);
        }).collect(Collectors.toList());
    }

    @Override
    public List<SimpleListByCollectionTypeVO> simpleListByCollectionAll(SaasTaskTypeEnum typeEnum) {
        return digitalCollectionDao.simpleListByCollectionAll(typeEnum);
    }


    public void fillingRedeem(GetDetailsBasedOnTheCollectionIdVO vo, DigitalCollectionProductInfo info) {
        Date now = new Date();
        vo.setRedeem(1);
        //设置的开始和结束时间不为空，且当前时间不在两个时间段内则无法购买，历史老商品未配置时间段的则为永久出售不做限制 区分已结束、未开始
        if (null != info.getBeginTime() && null != info.getEndTime()) {
            if (now.before(info.getBeginTime())) {
                vo.setRedeem(0);
            }
            if (now.after(info.getEndTime())) {
                vo.setRedeem(2);
            }

        }
    }


    @Override
    public CirculateDetailsDTO circulateDetails(Long collectionId) {
        CirculateDetailsDTO circulateDetailsDTO = new CirculateDetailsDTO();
        circulateDetailsDTO.setAirdropFrequency(airdropGrantRecordDao.getAirdropFrequencyById(collectionId));
        circulateDetailsDTO.setHoldCount(userCollectionDao.getCollectionCountByCollectionId(collectionId));
        circulateDetailsDTO.setHatchCount(userEcologyHatchRecordsDao.getSumHatchCountByCollectionId(collectionId));
        circulateDetailsDTO.setPledgeCount(userCollectionDao.getPledgeCountByCollectionId(collectionId));
        circulateDetailsDTO.setAirdropCount(airdropGrantRecordDao.getCountByCollectionId(collectionId));

        List<Long> collectionIds = Arrays.asList(collectionId);
        List<Long> userListByCollectionIds = userCollectionDao.getUserListByCollectionIds(collectionIds);
        circulateDetailsDTO.setHoldUserCount(userListByCollectionIds.size());
        circulateDetailsDTO.setHatchUserCount(userEcologyHatchRecordsDao.getHatchUserCountByCollectionId(collectionId));
        circulateDetailsDTO.setDestroyCount(userInfoDao.getOneDestroyCount(collectionId));
        return circulateDetailsDTO;
    }


    @Override
    public List<DigitalCollection> getCollectionListById(List<Long> releaseCollections) {
        if (CollectionUtils.isEmpty(releaseCollections)) {
            return new ArrayList<>();
        }
        return digitalCollectionDao.getByIds(releaseCollections);
    }


    /**
     * 获取给本dao分过账的数据
     *
     * @param daoId
     * @return
     */
    @Override
    public List<SimpleDigitalGetSeparateFundDTO> getDaoSeparateFund(Long daoId) {
        return ecologyHatchShareProfitDao.getDaoSeparateFund(daoId);
    }

    @Override
    public List<DigitalCollection> findListByDigitalMarketType(DigitalMarketTypeEnum digitalMarketTypeEnum) {
        return digitalCollectionDao.findListByDigitalMarketType(digitalMarketTypeEnum);
    }

}
